from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Dict, List
import uvicorn
import time
import uuid
import requests
import re

app = FastAPI(title="MCP Agent Server", description="A server for agent communication and task management")

# 配置CORS
# 生产环境注意事项：
# 1. 将allow_origins设置为特定域名，而不是"*"
# 2. 考虑限制allow_methods和allow_headers为必要的值
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中请修改为具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# In-memory storage for demonstration
agent_tasks = {}
agent_registry = {}

# Pydantic models
class AgentRegistration(BaseModel):
    agent_id: str
    name: str
    capabilities: List[str]

class TaskRequest(BaseModel):
    agent_id: str
    task_type: str
    parameters: Dict
    priority: Optional[int] = 1

class TaskResponse(BaseModel):
    task_id: str
    status: str
    result: Optional[Dict] = None
    error: Optional[str] = None

class SmsBatchSendRequest(BaseModel):
    phones: str
    smsContent: str
    sendtime: Optional[str] = None
    sendtermid: Optional[str] = None
    customTaskid: Optional[str] = None

# API Endpoints
@app.get("/", tags=["root"])
async def root():
    return {
        "message": "MCP Agent Server is running",
        "version": "1.0",
        "endpoints": {
            "register_agent": "/agents/register",
            "submit_task": "/tasks/submit",
            "get_task_status": "/tasks/{task_id}"
        }
    }

@app.post("/agents/register", tags=["agents"], response_model=dict)
async def register_agent(agent: AgentRegistration):
    if agent.agent_id in agent_registry:
        raise HTTPException(status_code=400, detail="Agent ID already registered")
    agent_registry[agent.agent_id] = {
        "name": agent.name,
        "capabilities": agent.capabilities,
        "last_seen": time.time()
    }
    return {
        "status": "success",
        "message": f"Agent {agent.name} registered successfully",
        "agent_id": agent.agent_id
    }

@app.post("/tasks/submit", tags=["tasks"], response_model=TaskResponse)
async def submit_task(task: TaskRequest):
    if task.agent_id not in agent_registry:
        raise HTTPException(status_code=404, detail="Agent not found")

    task_id = str(uuid.uuid4())
    agent_tasks[task_id] = {
        "agent_id": task.agent_id,
        "task_type": task.task_type,
        "parameters": task.parameters,
        "priority": task.priority,
        "status": "pending",
        "created_at": time.time(),
        "result": None,
        "error": None
    }

    # In a real implementation, this would be queued for processing
    # For demonstration, we'll mark it as completed immediately
    agent_tasks[task_id]["status"] = "completed"
    agent_tasks[task_id]["result"] = {"message": "Task processed successfully"}

    return TaskResponse(
        task_id=task_id,
        status=agent_tasks[task_id]["status"],
        result=agent_tasks[task_id]["result"]
    )

@app.get("/tasks/{task_id}", tags=["tasks"], response_model=TaskResponse)
async def get_task_status(task_id: str):
    if task_id not in agent_tasks:
        raise HTTPException(status_code=404, detail="Task not found")
    task = agent_tasks[task_id]
    return TaskResponse(
        task_id=task_id,
        status=task["status"],
        result=task["result"],
        error=task["error"]
    )

@app.get("/agents/list", tags=["agents"])
async def list_agents():
    return {
        "agents": [
            {
                "agent_id": agent_id,
                "name": details["name"],
                "capabilities": details["capabilities"],
                "last_seen": details["last_seen"]
            }
            for agent_id, details in agent_registry.items()
        ]
    }

@app.post("/sms/batch-send", tags=["sms"])
async def batch_send_sms(request: SmsBatchSendRequest):
    # 验证手机号码格式和数量
    phone_list = [p.strip() for p in request.phones.split(',') if p.strip()]
    if len(phone_list) > 1000:
        raise HTTPException(status_code=400, detail="最多支持1000个手机号码")
    phone_pattern = re.compile(r'^1[3-9]\d{9}$')
    for phone in phone_list:
        if not phone_pattern.match(phone):
            raise HTTPException(status_code=400, detail=f"手机号码格式不正确: {phone}")
    
    # 验证短信内容长度
    if len(request.smsContent) > 1000:
        raise HTTPException(status_code=400, detail="短信内容不能超过1000个字符")
    
    # 验证扩展号长度
    if request.sendtermid and len(request.sendtermid) > 12:
        raise HTTPException(status_code=400, detail="扩展号不能超过12位")
    
    # 验证客户任务ID长度
    if request.customTaskid and len(request.customTaskid) > 70:
        raise HTTPException(status_code=400, detail="客户任务ID不能超过70位")
    
    # 构建请求数据
    sms_data = {
        "phones": request.phones,
        "smsContent": request.smsContent,
        "sendtime": request.sendtime,
        "sendtermid": request.sendtermid,
        "customTaskid": request.customTaskid
    }
    
    # 发送请求到短信接口
    # 注意：请将以下URL替换为实际的短信接口地址
    try:
        response = requests.post(
            "http://ip:port/api/v2/sms/batchSend",  # 替换为实际短信接口地址
            json=sms_data,
            timeout=10
        )
        response.raise_for_status()  # 检查HTTP错误状态码
        response_data = response.json()
        
        if response_data.get("code") == 0:
            return {
                "code": 0,
                "msg": "success",
                "data": {"taskid": response_data["data"]["taskid"]}
            }
        else:
            return {
                "code": response_data.get("code", -1),
                "msg": response_data.get("msg", "短信接口返回错误")
            }
    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"调用短信接口失败: {str(e)}")
    except ValueError as e:
        raise HTTPException(status_code=500, detail=f"短信接口返回无效JSON: {str(e)}")

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)